package com.mycompany.myapp.service.impl;

import com.mycompany.myapp.service.CommodityService;
import com.mycompany.myapp.domain.Commodity;
import com.mycompany.myapp.repository.CommodityRepository;
import com.mycompany.myapp.service.dto.CommodityDTO;
import com.mycompany.myapp.service.mapper.CommodityMapper;
import com.mycompany.myapp.web.rest.utils.DateUtil;
import com.mycompany.myapp.web.rest.utils.ResultObj;
import com.mycompany.myapp.web.rest.utils.TypeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing {@link Commodity}.
 */
@Service
@Transactional
public class CommodityServiceImpl implements CommodityService {

    private final Logger log = LoggerFactory.getLogger(CommodityServiceImpl.class);

    private final CommodityRepository commodityRepository;

    private final CommodityMapper commodityMapper;

    public CommodityServiceImpl(CommodityRepository commodityRepository, CommodityMapper commodityMapper) {
        this.commodityRepository = commodityRepository;
        this.commodityMapper = commodityMapper;
    }

    /**
     * Save a commodity.
     *
     * @param commodityDTO the entity to save.
     * @return the persisted entity.
     */
    @Override
    public CommodityDTO save(CommodityDTO commodityDTO) {
        log.debug("Request to save Commodity : {}", commodityDTO);
        Commodity commodity = commodityMapper.toEntity(commodityDTO);
        commodity = commodityRepository.save(commodity);
        return commodityMapper.toDto(commodity);
    }

    /**
     * Get all the commodities.
     *
     * @return the list of entities.
     */
    @Override
    @Transactional(readOnly = true)
    public List<CommodityDTO> findAll() {
        log.debug("Request to get all Commodities");
        return commodityRepository.findAll().stream()
            .map(commodityMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
    }


    /**
     * Get one commodity by id.
     *
     * @param id the id of the entity.
     * @return the entity.
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<CommodityDTO> findOne(Long id) {
        log.debug("Request to get Commodity : {}", id);
        return commodityRepository.findById(id)
            .map(commodityMapper::toDto);
    }

    /**
     * Delete the commodity by id.
     *
     * @param id the id of the entity.
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete Commodity : {}", id);
        commodityRepository.deleteById(id);
    }

    public ResultObj insertCommodity(CommodityDTO commodityDTO) {
        Commodity commodity = commodityRepository.findCommodityByName(commodityDTO.getCname());
        if (!TypeUtils.isEmpty(commodityDTO)) {
            if (TypeUtils.isEmpty(commodity)) {
                commodity = new Commodity();
                commodity.setCname(commodityDTO.getCname());
                commodity.setStar(commodityDTO.getStar());
                commodity.setPrice(commodityDTO.getPrice());
                commodity.setImgUrl(commodityDTO.getImgUrl());
                commodity.setDetail(commodityDTO.getDetail());
                commodity.setModel(commodityDTO.getModel());
                commodity.setCount(commodityDTO.getCount());
                commodity.setBrand(commodityDTO.getBrand());
                commodity.setCreateTime(DateUtil.getZoneDateTime());
                commodity.setStatus("1");
                commodityRepository.save(commodity);
                return ResultObj.backInfo(true, 200, "新增成功！", null);
            }else{
                return ResultObj.backInfo(true, 201, "该商品已存在", null);
            }
        }
        return ResultObj.backInfo(false, 201, "新增失败!", null);
    }


    public Commodity findCommodityById(Long id) {
        return commodityRepository.findCommodityById(id);
    }


    /**
     * Get the commodity of index.
     *
     */
    @Override
    public List<CommodityDTO> getCommodityByFashionAndQuality(){
        log.debug("Request to get all indexCommodities");
        return commodityRepository.findCommodityByFashionAndQuality().stream()
            .map(commodityMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
    }

    public List<CommodityDTO> getTheLatestCommodity(){
        log.debug("Request to get all indexCommodities");
        Pageable pageable = PageRequest.of(0, 9);
        return commodityRepository.findTop9ByOrderByCreateTimeDesc(pageable).stream()
            .map(commodityMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
    }

    @Override
    public ResultObj updateCommodity(CommodityDTO commodityDTO) {
        Commodity commodity = findCommodityById(commodityDTO.getId());
        if (!TypeUtils.isEmpty(commodity) && commodityDTO.getCount() >= 0) {
            commodity.setCname(commodityDTO.getCname());
            commodity.setStar(commodityDTO.getStar());
            commodity.setPrice(commodityDTO.getPrice());
            commodity.setImgUrl(commodityDTO.getImgUrl());
            commodity.setDetail(commodityDTO.getDetail());
            commodity.setFashion(commodityDTO.getFashion());
            commodity.setQuality(commodityDTO.getQuality());
            commodity.setModel(commodityDTO.getModel());
            commodity.setCount(commodityDTO.getCount());
            commodity.setBrand(commodityDTO.getBrand());
            commodity.setStatus(commodityDTO.getStatus());
            commodityRepository.save(commodity);
            return ResultObj.backInfo(false, 200, "修改成功", null);
        }
        return ResultObj.backInfo(false, 200, "修改失败", null);
    }

    /**
     * find the commodity by type.
     *
     * @param type the type of the Commdoity.
     */
    public List<Commodity> findCommodityByType(String type){
        return commodityRepository.findCommodityByType(type);
    }

    /**
     * find the commodity by name.
     *
     * @param name the type of the Commdoity.
     */
    public Commodity findCommodityByName(String name){
        return commodityRepository.findCommodityByName(name);
    }

    @Override
    public ResultObj findGoodsByParams(int pageNum, int pageSize, String cname) {
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        Page<Commodity> commodities = commodityRepository.findByParams(cname,pageable);
        return ResultObj.back(200,commodities);
    }

    @Override
    public ResultObj deleteGoodsInfo(long id) {
        commodityRepository.findById(id).ifPresent(commodity -> {
            commodity.setStatus("0");
            commodityRepository.save(commodity);
        });
        return ResultObj.back(200,null);
    }


}
